package com.gxnu.edu.cn.ttxxt.service.Impl;

import com.gxnu.edu.cn.ttxxt.entity.Users;
import com.gxnu.edu.cn.ttxxt.mapper.UserRepository;
import com.gxnu.edu.cn.ttxxt.service.UserService;
import com.gxnu.edu.cn.ttxxt.util.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private JwtUtils jwtUtils; // 注入JwtUtils

    @Override
    public Map<String, Object> login(String username, String password, String ip) {
        Users users = userRepository.findByUsername(username);
        if (users == null) {
            throw new IllegalArgumentException("用户不存在");
        }

        // 直接对比密码
        if (!password.equals(users.getPasswordHash())) {
            throw new IllegalArgumentException("密码错误");
        }
        users.setIp(ip);
        userRepository.updateUsersIp(users);
        // 生成 JWT
        String token = jwtUtils.generateToken(users.getUserId(), users.getUsername());

        // 创建响应
        Map<String, Object> response = new HashMap<>();
        response.put("token", token);
        response.put("user", users);

        System.out.println("登录成功，用户信息: " + response.toString());
        return response;
    }
    @Override
    public int register(Users user) {
        // 检查用户名是否已存在
        if (userRepository.existsByUsername(user.getUsername())) {
            return 0; // 用户名已存在
        }

        // 检查手机号是否已存在
        if (StringUtils.hasText(user.getPhone()) && userRepository.existsByPhone(user.getPhone())) {
            return -1; // 手机号已存在
        }

        // 检查邮箱是否已存在
        if (StringUtils.hasText(user.getEmail()) && userRepository.existsByEmail(user.getEmail())) {
            return -2; // 邮箱已存在
        }


        // 设置默认值
        if (user.getAvatarUrl() == null) {
            user.setAvatarUrl("default_avatar.png");
        }
        if (user.getSignature() == null) {
            user.setSignature("这家伙很懒，什么都没留下");
        }
        if (user.getStatus() == null) {
            user.setStatus(1);
        }

        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());

        Random r = new Random();
        user.setUserId( r.nextLong() % 100000000000L);
        return userRepository.insert(user) > 0 ? 1 : -3; // 1=成功, -3=失败
    }


    @Override
    public Users findById(Long userId) {
        return userRepository.selectById1(userId);
    }

    @Override
    public Users findByUsername(String username) {
        return userRepository.findByUsername(username);
    }

    @Override
    public Users updateUserInfo(Long userId, String username, String phone,
                                String email ,String signature) {
        Users users = userRepository.selectById1(userId);
        if (users == null) {
            throw new IllegalArgumentException("用户不存在");
        }
            users.setUsername(username);
            users.setPhone(phone);
            users.setEmail(email);
        // 更新头像和签名
        users.setSignature(signature);
        users.setUpdateTime(LocalDateTime.now());
        userRepository.updateUsers(users);
        return users;
    }

    @Override
    public boolean changePassword(Long userId, String oldPassword, String newPassword) {
        Users users = userRepository.selectById(userId);
        if (users == null) {
            throw new IllegalArgumentException("用户不存在");
        }

        // 验证旧密码
        if (!oldPassword.equals(users.getPasswordHash())) {
            throw new IllegalArgumentException("旧密码不正确");
        }

        // 设置新密码
        users.setPasswordHash(newPassword);
        users.setUpdateTime(LocalDateTime.now());

        return userRepository.updateById(users) > 0;
    }

    @Override
    public boolean checkUsernameExists(String username) {
        return userRepository.existsByUsername(username);
    }

    @Override
    public boolean checkPhoneExists(String phone) {
        return userRepository.existsByPhone(phone);
    }

    @Override
    public boolean checkEmailExists(String email) {
        return userRepository.existsByEmail(email);
    }
}